<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '发布帖子',
    "enablePullDownRefresh": false,
  },
}
</route>
<template>
  <view class="page min-h-[100vh] bg-[#f4f4f4]">
    <k-navbar title="发布帖子"></k-navbar>

    <view class="mt-[46rpx] bg-white mx-[20rpx] px-[44rpx] rounded-sm min-[620rpx]">
      <wd-form ref="formRef" :model="model" :rules="rules">
        <wd-cell-group>
          <wd-cell title-width="0" prop="title">
            <wd-input v-model="model.title" placeholder="添加标题" custom-input-class="title-input"
              :no-border="true"></wd-input>
          </wd-cell>

          <wd-cell title-width="0" prop="content">
            <!-- <wd-textarea v-model="model.content" class="text-sm" placeholder="请输入发布内容" /> -->
            <sp-editor placeholder="请输入发布内容" :toolbar-config="{
              excludeKeys: ['link', 'export', 'video']
            }" @init="initEditor" @input="inputOver" @upinImage="upinImage" @upinVideo="handleUpinVideo"
              @exportHtml="exportHtml"></sp-editor>
          </wd-cell>

          <wd-cell title-width="0" prop="image">
            <wd-upload name="file" :limit="6" :header="header" multiple :file-list="state.fileList"
              image-mode="aspectFill" :action="action" @change="handleImageChange"></wd-upload>
          </wd-cell>
        </wd-cell-group>
      </wd-form>
    </view>

    <view class="m-[20rpx] bg-white rounded-sm  px-[30rpx] ">
      <!-- <wd-cell title="分类" value="请选择" is-link center /> -->
      <wd-select-picker label="分类" type="radio" value-key="id" label-key="name" custom-value-class="text-right"
        v-model="state.showCatePopup" :columns="state.cateList" @confirm="handleCateChange"></wd-select-picker>
    </view>

    <float-bottom customClass="min-h-[116rpx] flex items-center ">
      <view class="mx-[20rpx] w-full">
        <wd-button :round="false" custom-class="w-full" @click="handleSubmit">发布</wd-button>
      </view>
    </float-bottom>


  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { getEvnBaseUrl } from '@/utils'
import useUserStore from "@/store/user";
import { showToast, uploadFile } from "@/utils/uni";
import { toBack } from "@/utils/navigation";
import {
  fetchArticleCate,
  addArticle
} from "@/service/article";

const model = reactive({
  title: '',
  content: '',
  image: '',
  cid: ""
})

const userStore = useUserStore();
const header = computed(() => {
  return {
    token: userStore.token,
    version: import.meta.env.VITE_VERSION,
  }
});


const state = ref({
  fileList: [],
  cateList: [],
  showCatePopup: true,
  editorIns: null,
})

const rules = {
  title: [{ required: true, message: '请输入标题' }],
  content: [{ required: true, message: '请输入内容' }],
  image: [{ required: true, message: '请上传封面图片' }],
}

const action = computed(() => `${getEvnBaseUrl()}/shopapi/upload/image`)

const formRef = ref(null)
function handleCateChange({ value }) {
  model.cid = value
}

function getCate() {
  fetchArticleCate().then(res => {
    state.value.cateList = res.data.lists
  })
}

function handleImageChange({ fileList }) {
  model.image = fileList.map(item => {
    const res = JSON.parse(item.response);
    return res.data.url
  })
}


function handleSubmit() {
  if (!model.cid) {
    showToast("请选择分类")
    return
  }
  formRef.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        addArticle(model).then(res => {
          showToast("发布成功", toBack);
        })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

function initEditor(editor) {
  state.value.editorIns = editor // 保存编辑器实例
  // 保存编辑器实例后，可以在此处获取后端数据，并赋值给编辑器初始化内容
}


/**
 * 获取输入内容
 * @param {Object} e {html,text} 内容的html文本，和text文本
 */
function inputOver(e) {
  // 可以在此处获取到编辑器已编辑的内容
  console.log('==== inputOver :', e)
  model.content = e.html
  // state.value.editorIns.setContents({
  //   html: handleHtmlWithVideo(e.html)
  // })
}

function handleUpinVideo(tempFiles, editorCtx) {
  console.log(`editorCtx`, tempFiles);
  editorCtx.insertImage({
    src: 'https://admin.zhengtuqicheng.top/uploads/images/20250402142711dca068682.jpg',
    alt: tempFiles, // 携带视频真实地址
    width: '100%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
  })
}

/**
 * 直接运行示例工程插入图片无法正常显示的看这里
 * 因为插件默认采用云端存储图片的方式
 * 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
 * @param {Object} tempFiles
 * @param {Object} editorCtx
 */
function upinImage(tempFiles, editorCtx) {

  uni.showLoading({
    title: '上传中...',
    mask: true
  })
  Promise.all(tempFiles.map(path => {
    return uploadFile(path.tempFilePath)
  })).then(res => {
    res.forEach(item => {
      editorCtx.insertImage({
        src: item.data.uri,
        width: '100%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
      })
    })

  }).finally(uni.hideLoading)
}


onLoad(() => {
  getCate()
})
</script>

<style lang="scss" scoped>
.page {
  --wot-cell-value-color: #a8a8a8;
  @include addSafeArea(146rpx);
}

:deep(.wd-input__value) {
  padding-bottom: 20rpx;
  border-bottom: 4rpx dashed #A8A8A8;

  .title-input {
    font-size: 38rpx;

  }
}
</style>
